package net.pm.core.service.power.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import net.pm.common.dao.GenericDao;
import net.pm.common.service.impl.GenericServicerImpl;
import net.pm.common.toolkit.PMTool;
import net.pm.core.entities.db.Pmpower;
import net.pm.core.entities.db.Pmuser;
import net.pm.core.entities.db.UserPower;
import net.pm.core.service.power.UserPowerServicer;

import org.springframework.stereotype.Service;

@Service("UserPowerServicer")
public class UserPowerServicerImpl extends GenericServicerImpl<UserPower, Long>
		implements UserPowerServicer {

	@Resource(name = "UserPowerDao")
	@Override
	public void setGenericDao(GenericDao<UserPower, Long> genericDao) {
		super.genericDao = genericDao;
	}

	//改成用SQL...
	@Override
	public List<String> findUserPowerCodesByUserId(Long userId) {
		final StringBuilder builder = new StringBuilder(
				" from UserPower userpower where userpower.pmuser.id = ? ");
		List<UserPower> userpowers = super.findEntitiesByJpql(builder, userId);
		List<String> powers = new ArrayList<String>(userpowers.size());
		for (UserPower userpower : userpowers) {
			powers.add(userpower.getPmpower().getPowerCode());
		}
		return powers;
	}

	@Override
	public Long modifyUserPower(Long userId, Integer[] powerIds) {
		if (!this.findUserPowerCodesByUserId(userId).isEmpty())// 首先先清空,当前用户的权限
			this.removeUserPower(userId);
		// 进行更新
		List<UserPower> userpowers = new ArrayList<UserPower>();
		// 是否选择中其的新权限
		if (PMTool.isNotEmpty(powerIds) && powerIds.length > 0) {
			for (Integer id : powerIds) {
				UserPower userpower = new UserPower();
				userpower.setPmuser(new Pmuser(userId));
				userpower.setPmpower(new Pmpower(id));
				userpowers.add(userpower);
			}
			super.batchCreate(userpowers);
		}
		return UserPowerServicer.power_modify_success;
	}

	@Override
	public Long removeUserPower(Long userId) {
		final StringBuilder builder = new StringBuilder(
				" delete UserPower userpower where userpower.pmuser.id =  ? ");
		if (super.removeByJpql(builder, userId) > 0)
			return UserPowerServicer.power_remove_success;
		return UserPowerServicer.power_remove_failed;
	}

}
